package com.iwinding.ladygg.ui.act;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.iwinding.ladygg.R;
import com.iwinding.ladygg.constant.SPConstant;
import com.iwinding.ladygg.net.RequestManager;
import com.iwinding.ladygg.net.callback.BaseRpCallback;
import com.iwinding.ladygg.net.response.BaseRopnse;
import com.iwinding.ladygg.net.response.LoginRp;
import com.iwinding.ladygg.net.response.ThirdPartyLoginRp;
import com.iwinding.ladygg.ui.auth.QQAuthApi;
import com.iwinding.ladygg.ui.auth.WeiboAuthApi;
import com.iwinding.ladygg.ui.view.BottomWindowView;
import com.iwinding.ladygg.utils.FileUtil;
import com.iwinding.ladygg.utils.SPUtils;
import com.iwinding.ladygg.utils.SystemUtil;
import com.iwinding.ladygg.utils.ToastUtil;

/**
 * Created by hezhiyong on 2017/3/14.
 */

public class SettingActivity extends BaseActivity implements View.OnClickListener {


    @Override
    protected int getLayoutID() {
        return R.layout.icane_acvtivity_setting;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
    }

    void initView() {
        setBackTxtResId(R.string.bottom_tab_myself);
        setTitleResId(R.string.icane_my_setting);

        findViewById(R.id.lay_my_sos_prompt).setOnClickListener(this);
        findViewById(R.id.lay_my_change_phone).setOnClickListener(this);
        findViewById(R.id.lay_my_modify_password).setOnClickListener(this);
        findViewById(R.id.lay_my_clear_cache).setOnClickListener(this);
        findViewById(R.id.lay_my_like_we_encourage).setOnClickListener(this);
        findViewById(R.id.lay_my_about_us).setOnClickListener(this);
        findViewById(R.id.btn_my_exit_login).setOnClickListener(this);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.lay_my_sos_prompt:
                startActivity(new Intent(mContext, PromptActivity.class));
                break;
            case R.id.lay_my_change_phone:
                LoginRp loginRp = SystemUtil.getLoginRp(mContext);
                if (loginRp != null && TextUtils.isEmpty(loginRp.mobile)) {
                    startActivity(new Intent(mContext, BindPhoneActivity.class));
                    return;
                }
                startActivity(new Intent(mContext, ConfirmPhoneActivity.class));
                break;
            case R.id.lay_my_modify_password:
                startActivity(new Intent(mContext, ChangePwActivity.class));
                break;
            case R.id.lay_my_clear_cache:
                final BottomWindowView cacheWindow = createBwView(R.string.icane_clean_cache_prompt,
                        R.string.icane_delete,
                        R.string.icane_cancel);
                final AlertDialog dialog = createAlertDialog(this, cacheWindow);
                cacheWindow.setOnClick(new BottomWindowView.OnClick() {
                    @Override
                    public void onClickUp() {
                    }

                    @Override
                    public void onClickMid() {
                        FileUtil.deleteFile(mContext.getCacheDir().getPath());
                        dialog.dismiss();
                    }

                    @Override
                    public void onClickDown() {
                        dialog.dismiss();
                    }
                });
                showDialog(dialog);
                break;
            case R.id.lay_my_like_we_encourage:
                Uri uri = Uri.parse("market://details?id=" + getPackageName());
                Intent like_we = new Intent(Intent.ACTION_VIEW, uri);
                like_we.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(like_we);
                break;
            case R.id.lay_my_about_us:
                startActivity(new Intent(mContext, AboutUsActivity.class));
                break;
            case R.id.btn_my_exit_login:
                final BottomWindowView loginView = createBwView(R.string.icane_login_prompt,
                        R.string.icane_my_exit_login,
                        R.string.icane_cancel);
                final AlertDialog outDialog = createAlertDialog(this, loginView);
                loginView.setOnClick(new BottomWindowView.OnClick() {
                    @Override
                    public void onClickUp() {
                    }

                    @Override
                    public void onClickMid() {
                        logout();
                        outDialog.dismiss();
                    }

                    @Override
                    public void onClickDown() {
                        outDialog.dismiss();
                    }
                });
                showDialog(outDialog);
                break;
        }
    }

    void logout() {
        RequestManager.postLogout(mContext, new BaseRpCallback<BaseRopnse>() {

            @Override
            public BaseRopnse parseResponse(BaseRopnse response, int id) {
                return response;
            }

            @Override
            public void onResult(BaseRopnse baseRopnse) {
                if (mOAAplication.getmLoginRp() instanceof ThirdPartyLoginRp) {
                    ThirdPartyLoginRp thirdPartyLoginRp = SystemUtil.getThreeLoginRp(mContext);
                    if (!TextUtils.isEmpty(thirdPartyLoginRp.qqToken)) {
                        QQAuthApi.getInstance().logout();
                    }
                    if (!TextUtils.isEmpty(thirdPartyLoginRp.weiboToken)) {
                        WeiboAuthApi.getInstance().logout();
                    }
                }
                exit();
            }

            @Override
            public void onFail(String errorMsg) {
                ToastUtil.openBaseToast(mContext, errorMsg, Toast.LENGTH_SHORT);
            }
        });
    }

    private void exit() {
        EMClient.getInstance().logout(false,new EMCallBack(){

            @Override
            public void onSuccess() {
                SPUtils.putSpProperty(mContext, SPConstant.IS_EXIT, true);
                mOAAplication.setmLoginRp(null);
                SystemUtil.restartLogin(mContext);
                finish();
            }

            @Override
            public void onError(int code, String error) {
                SPUtils.putSpProperty(mContext, SPConstant.IS_EXIT, true);
                mOAAplication.setmLoginRp(null);
                SystemUtil.restartLogin(mContext);
                finish();
            }

            @Override
            public void onProgress(int progress, String status) {
            }
        });
    }

    AlertDialog createAlertDialog(Context mContext, View view) {
        return new AlertDialog.Builder(mContext)
                .setView(view)
                .create();
    }

    //创建弹窗
    PopupWindow createPopWin(View view) {
        // 创建PopupWindow对象
        PopupWindow pop = new PopupWindow(view, LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT, false);
        //LinearLayout.LayoutParams.MATCH_PARENT
        // 需要设置一下此参数，点击外边可消失
        pop.setBackgroundDrawable(new BitmapDrawable());
        // 设置点击窗口外边窗口消失
        pop.setOutsideTouchable(true);
        pop.setAnimationStyle(R.style.Anim_style);
        // 设置此参数获得焦点，否则无法点击
        pop.setFocusable(true);
        pop.setOnDismissListener(new PopupWindow.OnDismissListener() {

            @Override
            public void onDismiss() {
            }
        });
        return pop;
    }

    private BottomWindowView createBwView(int up, int mid, int down) {
        BottomWindowView cacheWindowView = new BottomWindowView(mContext);
        cacheWindowView.setText(getString(up), getString(mid), getString(down));
        final AlertDialog cacheWindow = createAlertDialog(this, cacheWindowView);
        cacheWindow.setCanceledOnTouchOutside(true);
        return cacheWindowView;
    }
    private void showDialog(AlertDialog cacheWindow){
        cacheWindow.show();
        Window window = cacheWindow.getWindow();
        window.setGravity(Gravity.BOTTOM);

        WindowManager m = getWindowManager();
        Display d = m.getDefaultDisplay(); //为获取屏幕宽、高
        WindowManager.LayoutParams p = cacheWindow.getWindow().getAttributes(); //获取对话框当前的参数值
        p.width = d.getWidth(); //宽度设置为屏幕
        cacheWindow.getWindow().setAttributes(p); //设置生效
    }

//    private void openPopupWindow(){
//

//        TextView textView = new TextView(mContext);
//        textView.setText("----------");
//        // TODO: 2016/5/17 创建PopupWindow对象，指定宽度和高度
//        PopupWindow window = new PopupWindow(textView, 400, 600);
//        // TODO: 2016/5/17 设置动画
//        window.setAnimationStyle(android.R.style.Animation_Dialog);
//        // TODO: 2016/5/17 设置背景颜色
//        window.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#F8F8F8")));
//        // TODO: 2016/5/17 设置可以获取焦点
//        window.setFocusable(true);
//        // TODO: 2016/5/17 设置可以触摸弹出框以外的区域
//        window.setOutsideTouchable(true);
//        // TODO：更新popupwindow的状态
//        window.update();
//        // TODO: 2016/5/17 以下拉的方式显示，并且可以设置显示的位置
//        window.showAsDropDown(getWindow().getDecorView().getRootView(),
//                -100, -100,Gravity.TOP);


//        PopupWindow pop = new PopupWindow(textView, LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT, false);
//        //LinearLayout.LayoutParams.MATCH_PARENT
//        // 需要设置一下此参数，点击外边可消失
//        ColorDrawable dw = new ColorDrawable(Color.parseColor("#00000000"));
//        // 设置SelectPicPopupWindow弹出窗体的背景
//        pop.setBackgroundDrawable(dw);
//        // 设置点击窗口外边窗口消失
//        pop.setOutsideTouchable(true);
//        pop.setAnimationStyle(android.R.style.Animation_Dialog);
//        // 设置此参数获得焦点，否则无法点击
//        pop.setFocusable(true);
//        pop.update();
//        pop.setOnDismissListener(new PopupWindow.OnDismissListener() {
//
//            @Override
//            public void onDismiss() {
//            }
//        });
//        pop.showAsDropDown(getWindow().getDecorView(), Gravity.BOTTOM, 0, 0);
//        boolean show = pop.isShowing();
//    }

}
